<script lang="ts" setup name="FixedModal">
import { NSelect } from 'naive-ui'
import Sortable from 'sortablejs'
import { useRoute } from 'vue-router'
import { DFModal, useModal } from '@/components/DFModal'

import { DFTable } from '@/components/DFTable'

import { useMixins } from '@/hooks/useMixins'

import { renderSvg } from '@/utils/index'

interface Props {
  tableContext?: Object
  setFieldInfoListFn?: Function
  confirmBtnShow?: boolean
  subBtuText?: string
}

const props = withDefaults(defineProps<Props>(), {
  tableContext: () => ({}),
  setFieldInfoListFn: () => {},
  confirmBtnShow: () => true,
  subBtuText: () => 'save',
})

const emit = defineEmits(['register', 'getFieldInfoListFn'])

const route: any = toRaw(useRoute())

// import { useDataSource } from './../hooks/useDataSource';

// const { getPageColumns } = useDataSource();

// console.log(getPageColumns);

const dfTable: any = ref(null)

const { message, getTableLabelFn, language, t } = useMixins()

// const basicModalRef: any = ref(null);

const subLoading = ref(false)

const [modalRegister, { openModal, closeModal }] = useModal({})

function setSubLoading(val = false) {
  subLoading.value = val
}

const tableColumns = [
  {
    width: 60,
    type: 'selection',
    key: 'selection',
  },
  {
    label: 'fieldName',
    key: 'fieldName',
    common: true,
    sorter: false,
  },
  {
    label: 'fixedColumn',
    key: 'fixedPosition',
    common: true,
    sorter: false,
    render(row) {
      return h(
        NSelect,
        reactive(({
          'options': [
            {
              label: t('common.table.unfixed'),
              value: 0,
            },
            {
              label: t('common.table.leftFixed'),
              value: 1,
            },
            {
              label: t('common.table.rightFixed'),
              value: 2,
            },
          ],
          'value': row.fixedPosition,
          'on-update:value': async (value) => {
            row.fixedPosition = value
          },
          'disabled': !multipleSelection.value.includes(row.field),
        }) as any),
      )
    },
  },
  {
    label: 'sort',
    common: true,
    sorter: false,
    align: 'center',
    className: 'sort-column',
    // title() {
    //   return h('div', {
    //     class: '123123123',
    //     width: '100%',
    //     'text-align': 'center',
    //     innerText: t(`common.table.sort`),
    //   });
    // },
    render(_row) {
      return h(renderSvg('fixedModalSort'), { class: 'fixed-modal-sort' })
    },
  },
]

async function okModalFn() {
  try {
    modalSubmitFn()
  }
  catch (e) {
    console.log(e)

    setSubLoading(false)
  }
}

async function modalSubmitFn() {
  try {
    subLoading.value = true

    const data: any = []

    const fixedList: any = []

    let hasSelected = false

    list.value.forEach((item, key) => {
      const { fixedPosition = 0, field = '' } = item

      if (field !== 'action') {
        const selected = multipleSelection.value.includes(field) ? 1 : 0

        const obj = {
          url: route.fullPath,
          fixedPosition,
          field,
          fieldOrder: key + 1,
          selected,
        }

        if (selected === 1)
          hasSelected = true

        if (fixedPosition !== 0)
          fixedList.push(obj)

        data.push(obj)
      }
    })

    if (!hasSelected) {
      message.error(t('common.tipMsg.fiexedModalErrTips1'))

      setSubLoading(false)

      return
    }

    if (fixedList.length > 10) {
      message.error(t('common.tipMsg.fiexedModalErrTips2'))

      setSubLoading(false)

      return
    }

    const res = await props.setFieldInfoListFn(data)

    if (res) {
      const { message: msg = '' } = res

      closeModal()

      msg && message.success(msg)

      emit('getFieldInfoListFn')

      setSubLoading(false)

      // emit('reloadFn');
    }
    else {
      setSubLoading(false)
    }
  }
  catch (e) {
    setSubLoading(false)

    console.log(e)
  }
}

const list: any = ref([])

const multipleSelection: any = ref([])

async function openModalFn() {
  const table: any = props.tableContext

  // 获取
  const getColumns = () => {
    const newRet: any[] = []
    table.getColumns().forEach((item) => {
      const { key = '' } = item

      if (key !== 'action' && key !== 'selection') {
        newRet.push({
          ...item,
          title: item.title || getTableLabelFn(item),
          width:
              language.value === 'zh' ? item.width || '' : item.widthEn ? item.widthEn : item.width,
        })
      }
    })
    return newRet
  }

  const columns: any[] = getColumns()

  list.value = []

  multipleSelection.value = []

  if (columns && columns.length) {
    columns
      .sort((a, b) => a.fieldOrder - b.fieldOrder)
      .forEach((item, _key) => {
        // console.log(item);
        const { label = '', ifShow = true, key: iKey = '', fixed = undefined } = item

        const ignoredColumn = ['action', 'selection']
        if (!ignoredColumn.includes(iKey)) {
          const obj = {
            fieldName: getTableLabelFn(item),
            fixedPosition: fixed === 'left' ? 1 : fixed === 'right' ? 2 : 0,
            index: list.value.length + 1,
            field: iKey || label,
          }

          list.value.push(obj)

          ifShow && multipleSelection.value.push(iKey || label)
        }
      })
  }

  // console.log(list.value);

  openModal(null, t('common.table.fixedTitle'))

  nextTick(() => {
    dfTable.value && dfTable.value.setTableData(list.value)

    nextTick(() => {
      // 需要支持拖动效果的列表容器，在这里我们设置为el-table组件的tbody，
      // 注意：最前面的一段为前面el-table的class: draggable-table，主要为了防止如果页面有多个table，多个table同时实现拖拽效果
      // 当然，如果多个table都需要拖拽效果，选择器中最前面的.draggable-table可以去除。
      const tbody = document.querySelector('.fixed-modal .n-data-table-tbody')

      new Sortable(tbody, {
        animation: 150,
        handle: '.fixed-modal-sort',
        filter: '.no-draggable',
        invertSwap: false,
        preventOnFilter: true,
        onSort(/** Event */ _evt) {
          // console.log('sort',evt)
          // 与 onEnd 相同的属性
        },
        onChange(_e, _a, _c) {
          // console.log('change',e)
          // console.log(a)
          // if(e.newIndex === 2){
          //   return false
          // }
        },
        onMove(/** Event */ _evt, /** Event */ _originalEvent) {
          // console.log('move',evt)
          // console.log(originalEvent)
          // if(evt.newIndex === 2){
          //   return false
          // }
          // return false
        },
        // 需要在odEnd方法中处理原始eltable数据，使原始数据与显示数据保持顺序一致
        onEnd: ({ newIndex, oldIndex }) => {
          // console.log(newIndex)

          // console.log(oldIndex)

          const targetRow = list.value[oldIndex]
          list.value.splice(oldIndex, 1)
          list.value.splice(newIndex, 0, targetRow)

          list.value.forEach((item, key) => {
            item.index = key + 1
          })

          // console.table(this.dialogTableDataList);
        },
      })
    })

    // console.log(dfTable.value);
  })
}

function changeMultipleSelectionFn(rowKeys) {
  multipleSelection.value = rowKeys

  for (const item of list.value) {
    const { field = '', fixedPosition = 0 } = item

    if (field && !rowKeys.includes(field) && fixedPosition !== 0)
      item.fixedPosition = 0
  }
}

function resetFieldsFn() {
  const table: any = props.tableContext

  const columns: any[] = table.getCacheColumns()

  list.value = []

  multipleSelection.value = []

  if (columns && columns.length) {
    columns.forEach((item, _key) => {
      const { label = '', ifShow = true, key: iKey = '', fixed = undefined } = item

      if (iKey !== 'action' && iKey !== 'selection') {
        const obj = {
          fieldName: getTableLabelFn(item),
          fixedPosition: fixed === 'left' ? 1 : fixed === 'right' ? 2 : 0,
          index: list.value.length + 1,
          field: iKey || label,
        }

        list.value.push(obj)

        ifShow && multipleSelection.value.push(iKey || label)
      }
    })
  }

  dfTable.value && dfTable.value.setTableData(list.value)

  // console.log(list.value);
}

// nextTick(() => {
//   const table: any = props.tableContext;

//   console.log(table);

//   //获取
//   const getColumns = () => {
//     let newRet: any[] = [];
//     table.getColumns().forEach((item) => {
//       newRet.push({
//         ...item,
//         title: item.title || getTableLabelFn(item),
//         width:
//           language.value === 'zh' ? item.width || '' : item.widthEn ? item.widthEn : item.width,
//       });
//     });
//     return newRet;
//   };

//   const columns: any[] = getColumns();

//   console.log(columns);
// });

// nextTick(() => {
//   openModalFn();
// });

defineExpose({ openModalFn })
</script>

<template>
  <DFModal
    ref="dfModal"
    class="fixed-modal basicModal"
    @register="modalRegister"
    @on-ok="okModalFn"
  >
    <template #default>
      <DFTable
        ref="dfTable"
        v-model:checked-row-keys="multipleSelection"
        :columns="tableColumns"
        :row-key="(row) => row.field"
        :pagination="false"
        :checked-row-key-model="true"
        :on-update:checked-row-keys="changeMultipleSelectionFn"
      />
    </template>
    <template #action>
      <div class="btns">
        <n-button @click="resetFieldsFn">
          <template #icon>
            <i class="iconfont icon-zhongzhi" />
          </template>{{ $t(`common.button.reset`) }}
        </n-button>
        <n-space>
          <n-button @click="closeModal">
            {{
              $t(`common.button.${confirmBtnShow ? 'cancel' : 'close'}`)
            }}
          </n-button>
          <n-button v-if="confirmBtnShow" type="primary" :loading="subLoading" @click="okModalFn">
            {{
              $t(`common.button.${props.subBtuText}`)
            }}
          </n-button>
        </n-space>
      </div>
    </template>
  </DFModal>
</template>

<style lang="less" scoped>
  .fixed-modal {
    .btns {
      // justify-content: flex-end;
      display: flex;
      justify-content: space-between;
      width: 100%;
      padding-top: 8px;
      // margin-bottom: 20px;
    }
  }
</style>

<style lang="less">
  .fixed-modal {
    .fixed-modal-sort {
      width: 18px;
      height: 18px;
      margin: 0 auto;
      cursor: move;
    }
  }
  .sort-column > .n-data-table-th__title-wrapper {
    justify-content: space-around;
  }
</style>
